<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户登录</title>
<link rel="stylesheet" href="ye.css">
</head>
<body>
<form id="loginForm" onsubmit="return validateForm()">
<fieldset>
<legend>用户登录</legend>
<div class="form-group">
<label for="username">用户名：</label>
<input type="text" id="username" name="username">
<span class="error" id="usernameError"></span>
</div>
<div class="form-group">
<label for="password">密码：</label>
<input type="password" id="password" name="password">
<span class="error" id="passwordError"></span>
</div>
<button type="submit">登录</button>
</fieldset>
</form>

<script>
function validateForm() {
const username = document.getElementById('username').value.trim();
const password = document.getElementById('password').value.trim();
let isValid = true;

// 清除旧错误信息
document.getElementById('usernameError').textContent = '';
document.getElementById('passwordError').textContent = '';

// 验证用户名
if (!username) {
showError('usernameError', '用户名不能为空');
isValid = false;
} else if (username.length < 8 || username.length > 20) {
showError('usernameError', '长度需为8-20个字符');
isValid = false;
}

// 验证密码
if (!password) {
showError('passwordError', '密码不能为空');
isValid = false;
} else if (password.length < 8 || password.length > 20) {
showError('passwordError', '长度需为8-20个字符');
isValid = false;
}

return isValid;
}

function showError(elementId, message) {
const errorElement = document.getElementById(elementId);
errorElement.textContent = message;
document.getElementById(elementId.replace('Error', '')).focus();
}
</script>
</body>
</html>